const {
	Service
} = require('uni-cloud-router')
const uniID = require('uni-id')
const dbUtil = require('db-util')
const moment = require('moment-timezone');

module.exports = class CustomerService extends Service {
	async recharge({
		customer,
		rechargeAmount,
		giveAmount
	}) {
		let dbCmd = this.db.command
		let transaction = await this.db.startTransaction()
		try {
			await dbUtil.insert({
				collection: 't3ds-customer-recharge',
				data: {
					customerId: customer._id,
					merchantId: customer.merchantId,
					amount: rechargeAmount,
					giveAmount,
					createTime: Date.now(),
					createBy: this.ctx.auth.uid
				},
				transaction
			})
			let t = rechargeAmount + giveAmount
			customer.balance += t
			customer.totalRechargeAmount += rechargeAmount
			customer.totalGiveAmount += giveAmount
			customer.updateTime = Date.now()
			customer.updateBy = this.ctx.auth.uid
			await dbUtil.updateById({
				collection: 't3ds-customer',
				data: customer,
				transaction
			})
			await transaction.commit()
			return {
				code: 200
			}
		} catch (e) {
			console.log("充值遇到错误", e);
			await transaction.rollback()
			return {
				code: 500,
				msg: e.message
			}
		}
	}
	
	async consume({
		customer,
		consumeAmount
	}) {
		let dbCmd = this.db.command
		let transaction = await this.db.startTransaction()
		try {
			await dbUtil.insert({
				collection: 't3ds-customer-consumption',
				data: {
					customerId: customer._id,
					merchantId: customer.merchantId,
					amount: consumeAmount,
					balanceBefore: customer.balance,
					balanceAfter: customer.balance - consumeAmount,
					createTime: Date.now(),
					createBy: this.ctx.auth.uid
				},
				transaction
			})
			customer.balance -= consumeAmount
			customer.updateTime = Date.now()
			customer.updateBy = this.ctx.auth.uid
			await dbUtil.updateById({
				collection: 't3ds-customer',
				data: customer,
				transaction
			})
			await transaction.commit()
			return {
				code: 200
			}
		} catch (e) {
			console.log("扣款遇到错误", e);
			await transaction.rollback()
			return {
				code: 500,
				msg: e.message
			}
		}
	}
}
